package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.StgyException;
import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.CreateBucketConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

  @Autowired private MinioProperties properties;
  @Autowired private MinioClient minioClient;

  @Override
  public String upload(MultipartFile file) {
    try {
      boolean bucketExists =
          minioClient.bucketExists(
              BucketExistsArgs.builder().bucket(properties.getBucketName()).build());
      if (!bucketExists) {
        minioClient.makeBucket(MakeBucketArgs.builder().bucket(properties.getBucketName()).build());
        //
        minioClient.setBucketPolicy(
            SetBucketPolicyArgs.builder()
                .bucket(properties.getBucketName())
                .config(createBucketPolicyConfig(properties.getBucketName()))
                .build());
      }
      // 文件名
      String filename =
          new SimpleDateFormat("yyyyMMdd").format(new Date())
              + "/"
              + UUID.randomUUID()
              + "-"
              + file.getOriginalFilename();

      // 放入桶中
      minioClient.putObject(
          PutObjectArgs.builder().bucket(properties.getBucketName()).object(filename).stream(
                  file.getInputStream(), file.getSize(), -1)
              .contentType(file.getContentType()) // stream类型会被浏览器下载 image类型才会直接在页面展示
              .build());
      // 返回url
      return properties.getEndpoint() + "/" + properties.getBucketName() + "/" + filename;
    } catch (Exception e) {
      throw new StgyException(ResultCodeEnum.FILE_UPLOAD_ERROR);
    }
  }

  @Override
  @Async // 异步删除
  public String delete(String path) {
    try {
      int beginIndex = (properties.getEndpoint()+"/"+properties.getBucketName()+"/").length();
      String objectName = path.substring(beginIndex);
      minioClient.removeObject(RemoveObjectArgs.builder()
              .bucket(properties.getBucketName())
              .object(objectName).build());
      return "success";
    } catch (Exception e) {
      throw new StgyException(ResultCodeEnum.FILE_DELETE_ERROR, e);
    }
  }

  private String createBucketPolicyConfig(String bucketName) {
  // 返回的JSON字符串 ‘%s’ 是占位符
    return """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """
        .formatted(bucketName);
  }
}
